s<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="分类名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入分类名称"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="排序字段" prop="sort">
        <el-input
          v-model="queryParams.sort"
          placeholder="请输入排序字段"
          clearable
          @input="validateSortField"
          @keyup.enter="handleQuery"
          type="number"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['service:service:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['service:service:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['service:service:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['service:service:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="serviceList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="分类ID" align="center" prop="id" />
      <el-table-column label="分类名称" align="center" prop="name" />
      <el-table-column label="排序字段" align="center" prop="sort" />
      <el-table-column label="状态" align="center" prop="status">
        <template #default="scope">
          <el-switch
            v-model="scope.row.status"
            :active-value="0"
            :inactive-value="1"
            :active-text="scope.row.status === 0 ? '可用' : ''"
            :inactive-text="scope.row.status === 1 ? '不可用' : ''"
            active-color="#13ce66"
            inactive-color="#ff4949"
            @change="(val) => handleStatusChange(scope.row, val)"
          />
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['service:service:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['service:service:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改服务分类对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="serviceRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="分类名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入分类名称" />
        </el-form-item>
        <el-form-item label="排序字段" prop="sort">
          <el-input 
            v-model="form.sort" 
            placeholder="请输入排序字段" 
            @input="validateFormSortField"
            type="number" 
          />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-switch
            v-model="form.status"
            :active-value="0"
            :inactive-value="1"
            active-text="可用"
            inactive-text="不可用"
            active-color="#13ce66"
            inactive-color="#ff4949"
          />
        </el-form-item>
        <el-form-item label="删除标志" prop="delFlag">
          <el-input v-model="form.delFlag" placeholder="请输入删除标志" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Service">
import { listService, getService, delService, addService, updateService } from "@/api/service/service"

const { proxy } = getCurrentInstance()

const serviceList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")
const isInitialLoad = ref(true)

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    name: null,
    sort: null,
    status: null,
  },
  rules: {
    name: [
      { required: true, message: "分类名称不能为空", trigger: "blur" }
    ],
  }
})

const { queryParams, form, rules } = toRefs(data)

/** 查询服务分类列表 */
function getList() {
  loading.value = true
  listService(queryParams.value).then(response => {
    // 确保数据格式正确
    serviceList.value = response.rows.map(item => {
      // 确保状态值是数字类型，以便正确绑定到开关组件
      if (item.status !== undefined) {
        item.status = Number(item.status);
      }
      return item;
    });
    total.value = response.total
    loading.value = false
    // 设置延时，确保列表数据加载完成后再允许状态变更操作
    setTimeout(() => {
      isInitialLoad.value = false
    }, 500)
  })
}

// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    name: null,
    sort: null,
    status: null,
    delFlag: null,
    createTime: null,
    updateTime: null
  }
  proxy.resetForm("serviceRef")
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  isInitialLoad.value = true
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef")
  isInitialLoad.value = true
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  open.value = true
  title.value = "添加服务分类"
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  const _id = row.id || ids.value
  getService(_id).then(response => {
    form.value = response.data
    // 确保状态值是数字类型
    if (form.value.status !== undefined) {
      form.value.status = Number(form.value.status)
    }
    open.value = true
    title.value = "修改服务分类"
  })
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["serviceRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updateService(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        })
      } else {
        addService(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功")
          open.value = false
          getList()
        })
      }
    }
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value
  proxy.$modal.confirm('是否确认删除服务分类编号为"' + _ids + '"的数据项？').then(function() {
    return delService(_ids)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => {})
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('service/service/export', {
    ...queryParams.value
  }, `service_${new Date().getTime()}.xlsx`)
}

/** 修改状态操作 */
function handleStatusChange(row, val) {
  // 如果是初始加载，不执行任何操作
  if (isInitialLoad.value) {
    return
  }
  
  let text = val === 0 ? "启用" : "停用";
  proxy.$modal.confirm('确认要' + text + '"' + row.name + '"服务分类吗?').then(function() {
    return updateService(row);
  }).then(() => {
    proxy.$modal.msgSuccess(text + "成功");
  }).catch(() => {
    row.status = val === 0 ? 1 : 0;
  });
}

/** 验证排序字段 */
function validateSortField() {
  if (queryParams.value.sort !== null && queryParams.value.sort !== '') {
    const num = Number(queryParams.value.sort);
    if (isNaN(num)) {
      proxy.$modal.msgError('排序字段必须为数字');
      queryParams.value.sort = null;
    }
  }
}

/** 验证表单排序字段 */
function validateFormSortField() {
  if (form.value.sort !== null && form.value.sort !== '') {
    const num = Number(form.value.sort);
    if (isNaN(num)) {
      proxy.$modal.msgError('排序字段必须为数字');
      form.value.sort = null;
    }
  }
}

getList()
</script>
